import { useEffect, useState } from 'react';
import { type Post } from '../types';
import { getHotPosts } from '../services/api';

export default function HotPostsPage() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchHotPosts = async () => {
      try {
        const data = await getHotPosts();
        setPosts(data);
      } catch (error) {
        if (error instanceof Error) {
          setError(error.message);
        } else {
          setError('An unknown error occurred');
        }
      }
    };

    fetchHotPosts();
  }, []);

  if (error) {
    return <div>Error: {error}</div>;
  }

  return (
    <div className="bg-white dark:bg-gray-900 py-8">
      <div className="mx-auto max-w-7xl px-6 lg:px-8">
        <h2 className="text-3xl font-bold tracking-tight text-gray-900 dark:text-white sm:text-4xl">Hot Posts</h2>
        <ul role="list" className="divide-y divide-gray-100 dark:divide-white/5">
          {posts.map((post) => (
            <li key={post.ID} className="flex justify-between gap-x-6 py-5">
              <div className="flex min-w-0 gap-x-4">
                <div className="min-w-0 flex-auto">
                  <a href={`/posts/${post.ID}`} className="text-sm/6 font-semibold text-gray-900 dark:text-white">{post.Title}</a>
                  <p className="mt-1 truncate text-xs/5 text-gray-500 dark:text-gray-400">by {post.Author}</p>
                </div>
              </div>
              <div className="hidden shrink-0 sm:flex sm:flex-col sm:items-end">
                <p className="text-sm/6 text-gray-900 dark:text-white">{new Date(post.CreatedAt).toLocaleDateString()}</p>
                <p className="mt-1 text-xs/5 text-gray-500 dark:text-gray-400">
                  Created at <time dateTime={post.CreatedAt}>{new Date(post.CreatedAt).toLocaleTimeString()}</time>
                </p>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};